# -*- coding:UTF-8 -*-
'''
Copyright 2009 http://code.google.com/p/mygaepy/. All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
  * Redistributions of source code must retain the above copyright
    notice, this list of conditions and the following disclaimer.
  * Redistributions in binary form must reproduce the above
    copyright notice, this list of conditions and the following
    disclaimer in the documentation and/or other materials provided
    with the distribution.
  * Neither the name of http://code.google.com/p/mygaepy/ nor the names of its
    contributors may be used to endorse or promote products derived
    from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
'''
import logging
import random
import time
import pickle
import StringIO
from struct import*

from google.appengine.api import memcache
from google.appengine.runtime import apiproxy_errors
from google.appengine.ext import db

from models import *

def getSysInfo():
    sysinfo = None
    try:
        sysinfo=memcache.get("SysInfo_")
    except apiproxy_errors.OverQuotaError, message:
        logging.error(message)
    if sysinfo is not None:
        return sysinfo
    query = db.GqlQuery ("SELECT * FROM SysInfo")
    results = query.fetch(1)
    if results:
        sysinfo = results[0]
        try:
            r=memcache.set("SysInfo_",sysinfo)
            if not r:
                logging.error("Memcache set sysinfo failed.")
        except apiproxy_errors.OverQuotaError, message:
            logging.error(message)
    else:
        sysinfo = SysInfo()
        sysinfo.put()
    return sysinfo

def setSysInfo(sysinfo):
    sysinfo.put()
    try:
        r=memcache.set("SysInfo_",sysinfo)
        if not r:
            logging.error("Memcache set sysinfo failed.")
    except apiproxy_errors.OverQuotaError, message:
        logging.error(message)

def getLogoByDay(domain, day):
  query = db.GqlQuery ("SELECT * FROM Logo WHERE domain=:1 AND showdate=DATE('%s')"%(day),domain)
  logos = query.fetch(1)
  if logos:
  	return logos[0]
  else:
  	return None

def getLogoInfo(limit):
    query=db.GqlQuery ("SELECT * FROM Logo ORDER BY showdate, domain LIMIT %d"%limit)
    return query.fetch(limit)

def getEBooks(offset=0,limit=20):
	query=db.GqlQuery ("SELECT * FROM eBookIndex WHERE bookid>=:1 ORDER BY bookid",offset)
	return query.fetch(limit)

def getNextBookId():
	query=db.GqlQuery ("SELECT * FROM eBookIndex ORDER BY bookid DESC LIMIT 1")
	books=query.fetch(1)
	if len(books)==0:
		return 1
	else:
		return books[0].bookid+1

def getBookIndexById(bookid):
	index=None
	try:
		index=memcache.get("ebook%dindexcache"%bookid)
		if index is None:
			query=db.GqlQuery ("SELECT * FROM eBookIndex WHERE bookid=:1", bookid)
			bookindex=query.fetch(1)
			if len(bookindex)!=0:
				bookindex=bookindex[0]
			else:
				return None
			logging.error(bookindex.bookindex)
			index=pickle.loads(bookindex.bookindex)
			memcache.set("ebook%dindexcache"%bookid,index)
	except apiproxy_errors.OverQuotaError, message:
		logging.error(message)
	return index

def getEbookData(bookid,partid):
	query=db.GqlQuery ("SELECT * FROM eBookData WHERE bookid=:1 AND partid=:2", bookid, partid)
	data=query.fetch(1)
	if len(data)==1:
		return data[0].zipdata
	else:
		return ''
	
def getImageServiceInfo():
	query = db.GqlQuery("SELECT * FROM ImageServiceInfo")
	info = query.fetch(1)
	if info:
		return info[0]
	else:
		info = ImageServiceInfo()
		info.nextimageid = 0
		info.byteused = 0
		info.put()
		return info

def getNextImageServiceId():
	info = getImageServiceInfo()
	id = info.nextimageid+1
	info.nextimageid=id
	info.put()
	return id
